import Axios from 'axios';
import Qs from 'qs';

//请求地址 
Axios.defaults.baseURL = 'http://minapp.duolaibei.com/admin/';   
//Axios.defaults.baseURL = 'https://api.huanglinjie.com/admin/';  
//请求头部   
Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//请求拦截
Axios.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    if (config.method == 'post'){
      config.data = Qs.stringify(config.data);
    }
    return config;
  }, 
  function (error) {
    //对请求错误做些什么
    return Promise.reject(error);
  }
);
let _ajaxSign = {};
export default function (
  { 
    method = "post", 
    url, 
    data = {}, 
    needToken = true,
    perfect,
    success,
    fail,
    only = true
  }
) {
  if (_ajaxSign[url] && only) {
    return;
  }
  _ajaxSign[url] = true;
  //验证是否需要token，以及token的正确性
  if (needToken) {
    let token = this.$store.state.user.token;
    if (!token) {
      this.$store.commit("user/setUserSign");
    }
    token = this.$store.state.user.token;
    if (token) {
      data.token = token;
    } else {
      //token失效，就清除用户登录信息
      this.$store.commit("user/removeUserSign");
      this.$router.push({ name: "route2" });
      return;
    }
  }
  Axios({
    method,
    url,
    data
  }).then((res) => {
    if (res.data.code === 1) {
      perfect && perfect(res.data.content, res);
    } else if (res.data.code === -1002 || res.data.code === -1001) {
      //token失效，就清除用户登录信息
      this.$store.commit("user/removeUserSign");
      this.$router.push({ name: "route2" });
      return;
    }
    success && success(res);
    delete _ajaxSign[url];
  }).catch((res) => {
    fail && fail(res);
    delete _ajaxSign[url];
  });
}